package com.iss.card.view.account;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.card.R;
import com.iss.card.cache.BitmapConfig;
import com.iss.card.cache.ImageCache;
import com.iss.card.cache.ImageDataManager;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CommonValue;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.UploadFileUtil;
import com.iss.card.model.UserInfo;
import com.iss.card.view.ContainerActivity;
import com.iss.card.webservice.WebServiceManager;

/**
 * �����ҵ�����ҳ��
 */
public class AccountFragment extends Fragment implements OnClickListener {
	private static final String TAG = AccountFragment.class.getSimpleName();
	private Activity mContext;

	private FrameLayout accountLoninLayout;
	private ImageView accountUsrHead;
	private TextView accountUsrInfo;
	private Button accountBtnLogin;

	private String dlgTitle = "Choice the image";
	private String items[] = { "From Gallary", "Take a Photo" };

	private final static int IMGFROMGALLARY = 1000;
	private final static int IMGFROMCAMERA = 2000;
	private final static int IMGFROMCROP = 3000;
	// private Uri mUri;
	private UserInfo usrInfo;
	private int headIconWidth;
	private int headIconHeight;
	private String imgName = "";
	/**
	 * Myself Content
	 */
	private TextView accoutAboutUs, accountFeedBack, accountChangeword,
			accountFirstUse;

	private void initView() {
		((TextView) accountLoninLayout.findViewById(R.id.job_name_val))
				.setText(R.string.tab_menu_account_info);
		accoutAboutUs = (TextView) accountLoninLayout
				.findViewById(R.id.about_us);
		accountFeedBack = (TextView) accountLoninLayout
				.findViewById(R.id.more_feedback);
		accountChangeword = (TextView) accountLoninLayout
				.findViewById(R.id.more_change_password);
		accountFirstUse = (TextView) accountLoninLayout
				.findViewById(R.id.more_first_use);

		accountUsrHead = (ImageView) accountLoninLayout
				.findViewById(R.id.account_user_info_head);
		accountUsrInfo = (TextView) accountLoninLayout
				.findViewById(R.id.account_user_info_mobile);
		accountBtnLogin = (Button) accountLoninLayout
				.findViewById(R.id.account_btn_login_logout);

		LinearLayout item1 = (LinearLayout) accountLoninLayout
				.findViewById(R.id.account_setting_more_funtion_item1);
		LinearLayout item3 = (LinearLayout) accountLoninLayout
				.findViewById(R.id.account_setting_more_funtion_item3);

		accoutAboutUs.setOnClickListener(this);
		accountFeedBack.setOnClickListener(this);
		accountChangeword.setOnClickListener(this);
		accountFirstUse.setOnClickListener(this);
		accountUsrHead.setOnClickListener(this);
		accountBtnLogin.setOnClickListener(this);

		if (FunctionUtil.isUserLogIn()) {
			usrInfo = FunctionUtil.getCurrentLogInUser();
			item1.setVisibility(View.VISIBLE);
			item3.setVisibility(View.VISIBLE);
			accountBtnLogin
					.setBackgroundResource(R.drawable.button_logout_setting);
			accountUsrInfo.setText(usrInfo.getUsrMobile());

			String iconPath = usrInfo.getUsrHeadIconUrl();
			Log.d(TAG, "iconPath=" + iconPath);
			if (CommonValue.STR_EMPTY.equals(iconPath)) {
				accountUsrHead.setImageBitmap(null);
			} else {
				ImageDataManager.instance().loadBitmap(iconPath,
						accountUsrHead,
						new BitmapConfig(headIconWidth, headIconHeight));
			}
		} else {
			item1.setVisibility(View.GONE);
			item3.setVisibility(View.GONE);
			accountBtnLogin
					.setBackgroundResource(R.drawable.button_login_setting);
			accountUsrHead.setImageBitmap(null);
			accountUsrInfo.setText(R.string.not_log_in);
		}

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mContext = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		usrInfo = FunctionUtil.getCurrentLogInUser();
		headIconWidth = (int) getResources().getDimension(
				R.dimen.DIM_ACCOUNT_HEAD_ICON_WIDTH);
		headIconHeight = (int) getResources().getDimension(
				R.dimen.DIM_ACCOUNT_HEAD_ICON_HEIGHT);
		dlgTitle = getResources().getString(R.string.account_choice_photo);
		items = getResources().getStringArray(R.array.account_get_photo_item);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.e(TAG, "onCreateView");
		accountLoninLayout = (FrameLayout) inflater.inflate(
				R.layout.frame_setting_view, null);
		initView();
		return accountLoninLayout;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG, "onResume");
		initView();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.e(TAG, "onPause");
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e(TAG, "onDestroy");
	}

	public void clear() {
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.about_us:

			Intent intentAbout = new Intent(mContext, ContainerActivity.class);
			intentAbout.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_ABOUT_US);
			mContext.startActivity(intentAbout);
			break;
		case R.id.more_change_password:
			Intent intentFroChangePW = new Intent(mContext,
					ContainerActivity.class);
			intentFroChangePW.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_CHANGE_PASSWORD);
			startActivity(intentFroChangePW);
			break;
		case R.id.more_feedback:

			Intent intentForFeed = new Intent(mContext, ContainerActivity.class);
			intentForFeed.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_FEED_BACK);
			startActivity(intentForFeed);
			break;
		case R.id.more_first_use:
			Intent intentForFirstUse = new Intent(mContext,
					ContainerActivity.class);
			intentForFirstUse.putExtra(ApplicationManager.INTENT_KEY,
					ApplicationManager.INTENT_FRAGMENT_FIRES_USE);
			startActivity(intentForFirstUse);
			break;
		case R.id.account_user_info_head:

			if (FunctionUtil.isUserLogIn()) {
				AlertDialog dlg = new AlertDialog.Builder(mContext)
						.setTitle(dlgTitle)
						.setItems(items, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int item) {
								// TODO Auto-generated method stub
								switch (item) {
								case 1:

									takeImgFromGallary();
									break;

								case 0:

									takeImgFromCamera();
									break;
								default:
									break;
								}
							}
						}).create();
				dlg.show();
			}

			break;
		case R.id.account_user_info_mobile:

			break;
		case R.id.account_btn_login_logout:

			if (FunctionUtil.isUserLogIn()) {
				AlertDialog dialog = new AlertDialog.Builder(mContext)
						.setTitle(
								mContext.getString(R.string.log_out_remind_title))
						.setMessage(
								mContext.getString(R.string.log_out_remind_content))
						.setPositiveButton(
								R.string.log_out_remind_confrim_button,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										doLogout();
									}
								})
						.setNegativeButton(
								R.string.log_out_remind_cancle_button,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								}).create();
				dialog.show();
			} else {
				doLogin();
			}
			break;

		default:
			break;
		}
	}

	private void takeImgFromGallary() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", headIconWidth);
		intent.putExtra("outputY", headIconHeight);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, IMGFROMGALLARY);

	}

	private void takeImgFromCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		imgName = createPicFileName();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imgName)));
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);  
		
		startActivityForResult(intent, IMGFROMCAMERA);
	}

	private void cropImg(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", headIconWidth);
		intent.putExtra("outputY", headIconHeight);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, IMGFROMCROP);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode,
			Intent data_intent) {
		super.onActivityResult(requestCode, resultCode, data_intent);

		if (resultCode == Activity.RESULT_OK) {
			Bitmap bmp = null;
			if (requestCode != IMGFROMCAMERA && data_intent == null) {
				return;
			}
			switch (requestCode) {
			case IMGFROMCAMERA:
				
				if(data_intent == null){
					cropImg(Uri.fromFile(new File(imgName)));
				}else {
					if(data_intent.getData() == null){
						String path = savePicToCard((Bitmap) data_intent.getExtras().getParcelable("data"));
						cropImg(Uri.fromFile(new File(path)));
					}else {
						cropImg(data_intent.getData());
					}
				}
				break;
			case IMGFROMGALLARY:
				bmp = data_intent.getParcelableExtra("data");
				UploadFileUtil.upload(WebServiceManager.uploadURL,
						convertBmpToInputStream(bmp), usrInfo.getUsrId());
				break;
			case IMGFROMCROP:
				bmp = data_intent.getParcelableExtra("data");
				UploadFileUtil.upload(WebServiceManager.uploadURL,
						convertBmpToInputStream(bmp), usrInfo.getUsrId());
				break;
			default:
				break;
			}
		}
	}

	private void doLogout() {
		FunctionUtil.saveCurrentLogInUser(null);
		ApplicationManager.accountIsLogin = false;
		initView();
	}

	private void doLogin() {
		Intent intentForLogin = new Intent(mContext, ContainerActivity.class);
		intentForLogin.putExtra(ApplicationManager.INTENT_KEY,
				ApplicationManager.INTENT_FRAMENT_LOG_IN);
		mContext.startActivity(intentForLogin);

	}

	private InputStream convertBmpToInputStream(Bitmap bmp) {
		ImageCache.instance().addBitmapToCache(
				UploadFileUtil.USR_HEAD_ICON_TEMP_NAME, bmp);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
		InputStream is = new ByteArrayInputStream(baos.toByteArray());
		return is;
	}

	private String savePicToCard(Bitmap bmp){
		String path = "";
		try {
			path =createPicFileName();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return path;
	}
	
	private String createPicFileName(){
		String path = "";
		String state = Environment.getExternalStorageState();  
        if (state.equals(Environment.MEDIA_MOUNTED)) {  
            File out_file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
            File dir = new File(out_file_path +File.separator +"eCard");  
            if (!dir.exists()) {  
                dir.mkdirs();  
            }  
            
            path =dir.toString() + File.separator +"MyPicture"+System.currentTimeMillis() + ".jpg";  
        }  
        else {  
            Toast.makeText(mContext, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }  
		return path;
	}
}
